<template>
  <el-container>
    <el-aside width="10%">

    </el-aside>
    <el-main>
      <el-row>
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>Article Editor</span>
              </div>
            </template>

            <div class="Editor-Main">
              <el-form ref="formRef" label-position="left" label-width="auto" :model="article" :rules="rules" status-icon>
                <el-form-item label="标题" prop="title">
                  <el-input placeholder="请输入标题" v-model="article.title"/>
                </el-form-item>
                <el-form-item label="概述" prop="abstracts">
                  <el-input placeholder="请输入文章概述" v-model="article.abstracts"/>
                </el-form-item>
                <el-form-item label="文章分类" prop="category">
                  <el-select placeholder="请选择文章分类" v-model="article.category" clearable>
                    <el-option label="技术分享" value="1"/>
                    <el-option label="学习笔记" value="2"/>
                    <el-option label="随心所写" value="3"/>
                    <el-option label="剑指Offer" value="4"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="文章封面" prop="coverurl">
                  <el-popover
                      placement="top-start"
                      title="上传策略"
                      trigger="hover"
                      content="可以点击图标 + 上传本地图片 , 也可以直接输入图片链接"
                  >
                    <template #reference>
                      <el-upload
                          ref="upload"
                          class="avatar-uploader"
                          :before-upload="beforeUpload"
                          :limit="1"
                          action="/api/upload"
                          name="file"
                          :headers="{'Authorization':tokenStore.token}"
                          :on-success="handleCoverSuccess"
                          :on-exceed="handleExceed"
                          :auto-upload="false"
                      >
                        <el-image v-if="imageUrl" class="avatar" :fit="'fill'" :src="imageUrl"/>
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                      </el-upload>

                    </template>
                  </el-popover>
                  <el-button type="success" @click="submitUpload">
                    上传文件
                  </el-button>
                  <el-input placeholder="输入封面url地址" v-model="article.coverurl"/>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                  <!--toolbarsExclude="['link', 'mermaid', 'katex', 'github', 'save']"意思是隐藏一些按钮-->
                  <MdEditor
                      v-model="article.content"
                      @onUploadImg="onUploadImg"
                      toolbarsExclude="['save']"
                      style="text-align: left"/>
                </el-form-item>
                <el-form-item label=" ">
                  <el-button type="primary" @click="submitForm">发布文章</el-button>
                  <el-button>取消</el-button>
                </el-form-item>
              </el-form>
            </div>
            <template #footer>
              <span>发布成功后等待管理员审核</span>
              <span>审核成功后即可在主页展示</span>
            </template>
          </el-card>
        </el-col>
      </el-row>
    </el-main>

    <el-aside width="10%">

    </el-aside>
  </el-container>

</template>

<script setup lang="ts">
import {useRouter} from "vue-router"
// 引入md-editor-v3插件
import {MdEditor} from "md-editor-v3"
import 'md-editor-v3/lib/style.css'
import {ref} from "vue"
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios';

//导入token
import {useTokenStore} from '/src/stores/token.js'
//导入userinfostore
import useUserInfoStore from '/src/stores/userInfo.js'

import {articleAddService} from '/src/api/Article.js'


const content = ref('')
const DialogVisible = ref(false)
const imageUrl = ref('')


const article = ref({
  id:0,
  userid:0,
  title:"",
  coverurl:"",
  abstracts:"",
  content:"",
  category:null,
  createtime:"",
  updatetime:"",
  status:0,
  message:"",
  likenumber:0
})

//文章表单
const formRef = ref(null);

//定义表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 16, message: '长度为2~16位非空字符', trigger: 'blur' }
  ],
  abstracts: [
    { required: true, message: '请输入文章概述', trigger: 'blur' },
    { min: 5, max: 50, message: '长度为5~50位非空字符', trigger: 'blur' }
  ],
  category:[
    {required:true,message:'请选择分类',trigger:'change'},
  ],
  // content: [
  //   { required: true, message: '请输入文章内容', trigger: 'blur' },
  //   // { min: 5, max: 50, message: '长度为5~50位非空字符', trigger: 'blur' }
  // ]
}

//获取token
const tokenStore = useTokenStore();
//获取用户信息
const userInfoStore = useUserInfoStore();

const router = useRouter()

//上传文件函数
const handleCoverSuccess = (result) => {

  imageUrl.value = result.data
  article.value.coverurl = imageUrl.value

}

import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { genFileId } from 'element-plus'

const upload = ref<UploadInstance>()

//设置 limit 和 on-exceed 可以在选中时自动替换上一个文件
const handleExceed :UploadProps['onExceed'] = (files) => {
  if(upload.value)
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const submitUpload = () => {
  upload.value!.submit()
}

// 校验用户选择的文件
const beforeUpload = (file) => {

  const isJPG =
      file.type === 'image/jpeg' ||
      'image/jpg' ||
      'image/png';
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isJPG) {
    ElMessage.error(
        '上传封面图片只能是 JPG、JPEG或PNG 格式!'
    );
  }
  if (!isLt5M) {
    ElMessage.error('上传头像图片大小不能超过 5MB!');
  }

  return isJPG && isLt5M;

}



// 表单提交
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 通过验证，执行提交操作
      // ElMessage.success('验证成功')
      // 在这里发出请求
      addArticle()

    } else {
      ElMessage.error("验证失败")
      return false;

    }
  });
};

//添加文章功能
const addArticle = () => {

  ElMessageBox.confirm(
      '您确认要提交吗?',
      '温馨提示',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
      )
      .then(async () => {
        //
        if(article.value.content === ''){
          ElMessage.error('内容不能为空!')
          return
        }
        //1.
        let result = await articleAddService(article.value)
        ElMessage.success('发布成功')

        //2.
        router.push('/articlemanage')
      })
      .catch(() => {
        ElMessage.error('取消发布!')
      })

}

// markdown编辑器中图片上传函数
const onUploadImg = async (files, callback) => {
  try {
    const res = await Promise.all(
        files.map((file) => {
          const form = new FormData();
          form.append('file', file);
          const isLt5M = files.size / 1024 / 1024 > 5;
          if(isLt5M){
            ElMessage.error("图片大小不能超过5M!")
            return ;
          }

          return axios.post('/api/upload', form, {
            headers: {
              'Authorization': tokenStore.token,
              'Content-Type': 'multipart/form-data'
            }
          });
        })
    );


    let url = res.map((item) => item.data.data);
    // 将图片URL以Markdown图片语法插入到编辑器内容中
    article.value.content += "![Image]("+url+")";

    //以下代码为测试res返回内容
    // console.log(res)
    // callback(res.map((item) => item.data));
    //console.log(url)

    // 将图片URL以Markdown图片语法插入到编辑器内容中
    // url.forEach(url => {
    //   article.value.content += "![Image]("+url.data+")";
    // });

  } catch (error) {
    ElMessage.error("上传失败!")
    console.error("Image upload failed: ", error);
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>